/**
 * Sleeper.java
 */
package com.mht2017.common.utils;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

public class Waiter {

	private static final Logger LOGGER = Logger.getLogger(Waiter.class);

	private ReentrantLock lock = new ReentrantLock();
	private Condition sleepCondition = lock.newCondition();

	private String actionName;

	public Waiter(String actionName) {
		this.actionName = actionName;
		LOGGER.info(String.format("%s-创建等待器", actionName));
	}

	public void await() {
		try {
			lock.lockInterruptibly();
			sleepCondition.await();
		} catch (InterruptedException e) {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug(String.format("%s-等待被打断: '%s'", actionName, e.getMessage()));
			}
		} finally {
			lock.unlock();
		}
	}

	public void wakeup() {
		try {
			lock.lock();
			sleepCondition.signal();
		} finally {
			lock.unlock();
		}
	}
}
